<?php

namespace App\Http\Controllers\Logic;

use App\Helpers\ArrayHelper;
use App\Http\Controllers\Constant\Constant;
use App\Http\Controllers\Controller;
use App\Model\OAAdmin;
use App\Model\OAFiles;
use App\Model\OAFinance;
use App\Model\OAProjectLx;
use App\Model\OAProjectYs;
use App\Model\OAShenPiLog;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;

class ShenPiLogLogic extends Controller
{
    //添加审批日志
    public function addShenPiLog($params)
    {
        #1.新旧数据对比
        try {
            $newData = $params['newData'];
            $type = $params['type'];
            unset($newData['history']);
            $log = $this->checkDifferentData($newData, $type);
           // dd($log);
            if($type == 'ys'){
                $logLx = $this->checkDifferentData(Arr::get($newData,'baseInfo'),'lx');
                if($logLx && is_array($logLx) && is_array($log)){
                    $log = array_merge($logLx,$log);
                }
            }
            //审批附件必选先保存后审批
            $nothingShenPiLog = OAShenPiLog::getNothingShenPiLog($newData['work_id'],$newData['id']);
            $spTip = '';
            if ($fileList = Arr::get($params,'fileList',[])) {
                if(is_null($nothingShenPiLog)){
                    $spTip = "审批附件未保存";
                }else{
                    //DB::enableQueryLog();
                   $hasSaveNames = OAFiles::query()
                        ->where('pid',$nothingShenPiLog->id)
                        ->where('type', OAFiles::FILE_TYPE_TEMP)
                        ->where('work_id',$newData['work_id'])
                        ->pluck("name")
                       ->toArray();
                   //dd(DB::getQueryLog());
                     $fileNames = array_column($fileList,"fileName");
                     //dd($fileNames,$hasSaveNames);
                     if(!ArrayHelper::arrays_are_same($hasSaveNames,$fileNames)){
                         $spTip = "审批附件有更改";
                     }
                }
                if($spTip){
                    if(is_array($log)){
                        $log[] = $spTip;
                    }elseif(is_string($log)){
                        $log = sprintf("%s,%s",$log,$spTip);
                    }else{
                        $log = $spTip;
                    }
                };
            }
                //dd($log);
            $tips = is_array($log) ? '您有修改信息,请立即修改' : '您有保存的信息,尚未修改,请立即修改';
            $note = $params['note'];
            if ($params['position_id'] == Constant::ROLE_SHEN_JI && in_array($type, ['cw', 'xz'])) {
                $this->checkHzdRepeat($newData);
            }

            if($type == 'ys' && $params['position_id'] == Constant::ROLE_CAIGOU){
                if(empty($newData['seller_id'])) throw new \Exception("请选择销售经理");
            }

            if($type == 'lx' && $params['position_id'] == Constant::ROLE_ZONGJILI && $params['state']){
                if(empty($newData['partner_id'])) throw new \Exception("请选择客户名称");
            }

            $isChange = false;
            if ($log) $isChange = true;
            //没有修改时才能够通过审批
            if (!$isChange) {
                if ($nothingShenPiLog) {
                    $logId = $nothingShenPiLog->id;
                    $nothingShenPiLog->status = Arr::get($params, 'state');
                    $nothingShenPiLog->note = $note;
                    $nothingShenPiLog->save();
                }else{
                    $splog = OAShenPiLog::createShenPiLogs($newData['work_id'],$newData['id'],Arr::get($params, 'note'),Arr::get($params, 'state'));
                    $logId = $splog->id;
                }
                if ($fileList = Arr::get($params,'fileList',[])) {
                    $this->saveFileList($logId, $fileList, FILE_LOG,$newData['work_id']);
                }
            }
            return ['is_change' => $isChange,'tips'=>$tips,'log'=>$log];
        }catch (\Exception $e){
            //dump($e);
            throw new \Exception($e->getMessage());
        }

    }

    //修改审批状态
    public function editProjectState($params)
    {
        $type = $params['type'];

        switch ($type){
            case 'lx':
                $query = OAProjectLx::query();
                break;
            case 'ys':
            case 'js':
                $query = OAProjectYs::query();
                break;
            case 'cw':
                $query = OAFinance::query();
                break;
            case 'xz':
                $query = OAAdmin::query();
                break;
            default:
                $query =  OAProjectLx::query();
        }
        $id = $params['id'];
        $state = $params['state'];
        DB::beginTransaction();
        try{
            $info = $query->where('id',$id)->first();
            //获取下个审批角色
            $returnWorkList = config('oa.returnWorkList');
            $work_list = isset($returnWorkList[$info->work_id]) ? $returnWorkList[$info->work_id] : [];
            //dd($work_list);
            if(in_array($info->work_id,$work_list)){
                $nextApprover = $this->getYaJinReturn($params,$info);
            }else{
                $nextApprover = $this->getNextApprover($info->node_id,$info->work_id,$state);
                $nextApprover['work_id'] = $info->work_id;
            }
            $info->node_id = $nextApprover['node_id'];
            $info->roleid = $nextApprover['roleid'];
            $info->status = $nextApprover['status'];
            $info->work_id = $nextApprover['work_id'];
            $info->is_save = 0;
            $info->save();
            DB::commit();

            return true;

        }catch (\Exception $e){
            DB::rollBack();
            throw new \Exception($e->getMessage());
        }
    }
}
